/*
 * FileName: HttpSocket.java
 * Author:   zzw
 * Date:     2018年04月28日
 * Description: http socket
 */
package com.zzw.basic.socket.http;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 〈http socket〉<br>
 * 〈http socket〉
 *
 * @author zzw
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本]（可选）
 */
public class HttpSocket {

    private static final String OUTPUT = "<html><head><title>Example</title></head><body><p>Worked!!!</p></body></html>";
    private static final String OUTPUT_HEADERS = "HTTP/1.1 200 OK\r\n" +
            "Content-Type: text/html\r\n" +
            "Content-Length: ";
    private static final String OUTPUT_END_OF_HEADERS = "\r\n\r\n";

    public void start() {
        try {
            ServerSocket serverSocket = new ServerSocket(9002);
            boolean isStop = false;

            while (!isStop) {
                Socket socket = serverSocket.accept();
                InputStream in = socket.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
                String line = null;
                while ((line = bufferedReader.readLine())!=null){
                    System.out.println(line);
                    if (line.isEmpty()) {
                        break;
                    }
                }
                sendResponse(socket);
                socket.close();

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void sendResponse(Socket socket) throws IOException {
        OutputStream outputStream = socket.getOutputStream();
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream));
        bw.write(OUTPUT_HEADERS + OUTPUT.length() + OUTPUT_END_OF_HEADERS + OUTPUT);
        bw.flush();
        bw.close();
    }

    public static void main(String[] args){
        new HttpSocket().start();
    }
}
